var express = require('express');

var router = express.Router();

const User = require('../models/users')


//统一返回格式
var responseData;
router.use(function (req, res, next) {
    responseData = {
        code: 0,
        msg: ''
    }
    next();
})

// 注册
router.post('/user/register', function (req, res) {
    console.log('req.bodyusername',req.body);
    const username = req.body.username;
    const password = req.body.password;
    const qrPwd = req.body.repassword;
    console.log(req.body);
    if (!username) {
        res.json({
            code: 0,
            msg: '用户名不能为空'
        })
    }
    if (!password) {
        res.json({
            code: 0,
            msg: '密码不能为空'
        })
    }
    if (password != qrPwd) {
        res.json({
            code: 0,
            msg: '两次密码不一致'
        })
    }
    User.findOne({
        username: username
    }).then(info => {
        if (info) {
            responseData = {
                code: 1,
                msg: '用户名已存在'
            }
            res.json(responseData)
        } else {
            const user = new User({
                username: username,
                password: password
            })
            return user.save()
        }
    }).then(newInfo => {
        responseData = {
            code: 2,
            msg: '注册成功'
        }
        res.json(responseData)
    })
})

// login
router.post('/user/login', function (req, res) {
    const username = req.body.username;
    const password = req.body.password;
    if (!username) {
        responseData = {
            code: 1,
            msg: '用户名不能为空'
        }
        res.json(responseData)
    }
    if (!password) {
        responseData = {
            code: 1,
            msg: '密码不能为空'
        }
        res.json(responseData)
    }
    User.findOne({
        username: username,
        password: password
    }).then(info => {
        if(!info){
            responseData = {
                code: 1,
                msg: '用户名密码有误'
            }
            res.json(responseData)
        }else {
            responseData = {
                code: 0,
                msg: '登陆成功',
                userInfo:{
                    _id :info._id,
                    username:info.username
                }
            }
            // 发送cookies信息给浏览器
            req.cookies.set('userInfo',JSON.stringify({
                _id :info._id,
                username:info.username
            }));
            res.json(responseData)
        }
    })
})

// 退出
router.get('/user/logout',function (req,res) {
    req.cookies.set('userInfo',null)
    res.json(responseData);
})
module.exports = router;